package com.ikun.kunpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ikun.kunpicturebackend.annotation.AuthCheck;
import com.ikun.kunpicturebackend.common.BaseResponse;
import com.ikun.kunpicturebackend.common.DeleteRequest;
import com.ikun.kunpicturebackend.common.ResultUtils;
import com.ikun.kunpicturebackend.constant.UserConstant;
import com.ikun.kunpicturebackend.domain.Space;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.manager.auth.SpaceUserAuthManager;
import com.ikun.kunpicturebackend.model.dto.space.SpaceAddRequest;
import com.ikun.kunpicturebackend.model.dto.space.SpaceEditRequest;
import com.ikun.kunpicturebackend.model.dto.space.SpaceQueryRequest;
import com.ikun.kunpicturebackend.model.dto.space.SpaceUpdateRequest;
import com.ikun.kunpicturebackend.model.enums.SpaceLevelEnum;
import com.ikun.kunpicturebackend.model.vo.SpaceLevel;
import com.ikun.kunpicturebackend.model.vo.SpaceVO;
import com.ikun.kunpicturebackend.service.SpaceService;
import com.ikun.kunpicturebackend.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 更新空间信息
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest updateRequest) {
        ThrowUtils.throwIf(updateRequest == null || updateRequest.getId() <= 0,
                ErrorCode.PARAMS_ERROR);

        Space space = new Space();
        BeanUtil.copyProperties(updateRequest, space);
        // 填充空间限额信息
        spaceService.fillSpaceBySpaceLevel(space);
        // 校验
        spaceService.validSpace(space, false);

        Space byId = spaceService.getById(space.getId());
        ThrowUtils.throwIf(byId == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");

        boolean update = spaceService.updateById(space);
        ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR, "更新失败");
        return ResultUtils.success(true);
    }

    /**
     * 删除空间
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0,
                ErrorCode.PARAMS_ERROR);

        // 待删空间id
        Long id = deleteRequest.getId();
        // 查询空间信息
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        // 只有空间创建人和管理员能删除
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        spaceService.checkSpaceAuth(loginUser, space);

        // 删除空间
        boolean result = spaceService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除空间失败");
        return ResultUtils.success(true);
    }

    /**
     * 编辑空间
     * @param editRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest editRequest, HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(editRequest == null || editRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);

        // 将请求转换为Picture
        Space space = new Space();
        BeanUtil.copyProperties(editRequest, space);
        // 设置编辑时间
        space.setEditTime(new Date());

        // 空间校验
        spaceService.validSpace(space, false);

        // 查询空间，判断是否存在
        Space oldSpace = spaceService.getById(space.getId());
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        // 判断是否是本人操作或管理员
        User loginUser = userService.getLoginUser(request);
        spaceService.checkSpaceAuth(loginUser, oldSpace);

        // 操作数据库，更新空间
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 新增空间
     * @param addRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest addRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(addRequest == null || request == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Long result = spaceService.addSpace(addRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 获取空间级别列表
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel() {
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values()) // 获取所有枚举
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

    /**
     * 根据 id 获取空间【管理员】
     */
    @GetMapping("/get")
    @AuthCheck
    public BaseResponse<Space> getSpaceById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据 id 获取空间（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        // 获取权限
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表 【管理员】
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        // 查询条件
        QueryWrapper<Space> queryWrapper = spaceService.getQueryWrapper(spaceQueryRequest);
        // 分页查询
        Page<Space> page = spaceService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(page);
    }

    /**
     * 分页获取空间列表（封装类）
     * @param spaceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                         HttpServletRequest request) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        // 分页查询
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize), spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }
}
